package com.xydpeng.rpc.protocol;

import lombok.Getter;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2023/4/10
 * @description:
 */
@Getter
public class ServiceMeta<T> {

    private Class<?> interfaceClass;
    private transient T ref;
    private Method[] methods;
    private int[] methodIds;
    private Map<Integer, HandlerMeta> handlerMetaMap;

    public ServiceMeta(Class<?> interfaceClass, T ref) {
        this.interfaceClass = interfaceClass;
        this.ref = ref;
        this.methods = interfaceClass.getDeclaredMethods() == null ? new Method[0] : interfaceClass.getDeclaredMethods();
        this.methodIds = new int[methods.length];
        this.handlerMetaMap = new HashMap<>(methods.length);
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            HandlerMeta<Object> handlerMeta = new HandlerMeta<>(interfaceClass, ref, method);
            methodIds[i] = handlerMeta.getHandlerId();
            if (handlerMetaMap.containsKey(handlerMeta.getHandlerId())) {
                throw new IllegalStateException("interfaceClass method methodId has conflicted:" + handlerMeta.getFullMethodName() + " vs " + handlerMetaMap.get(handlerMeta.getHandlerId()).getFullMethodName());
            }
            handlerMetaMap.put(handlerMeta.getHandlerId(), handlerMeta);
        }
    }
}
